package com.aaa.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {


    @Override  // 在容器加载时调用
    public void init(FilterConfig filterConfig) throws ServletException {


    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("LoginFilter---doFilter");

        // 向下转型
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        String url = httpServletRequest.getRequestURI();
        // 获取session
        HttpSession httpSession = httpServletRequest.getSession();

        Object object =  httpSession.getAttribute("login");

        boolean login = false;
        if (object!=null){
            login = (boolean) object;
        }

        if (login || url.contains("login.html") || url.contains("LoginServlet")||url.contains("css")||url.contains("js")||url.contains("img")||url.contains("common")){
            // 放行  将拦截方向传递 下一个拦截器
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            // 若
            httpServletResponse.sendRedirect("/login/login.html");
        }


    }

    @Override   // 在容器销毁的时候调用
    public void destroy() {
        System.out.println("LoginFilter---destroy");
    }


}
